package com.kkb.controller;

import com.kkb.domain.AjaxResult;
import com.kkb.page.QueryPageBean;
import com.kkb.page.TableDataInfo;
import com.kkb.pojo.TCourse;
import com.kkb.pojo.TUser;
import com.kkb.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.List;

import static com.kkb.constant.GlobalConst.SESSION_KEY_USER;

/**
 * 学科控制层
 */
@Controller
public class CourseController extends BaseController {
    @Autowired
    private CourseService courseService;

    @PostMapping("/course/add")
    @ResponseBody
    public AjaxResult addCourse(@Validated @RequestBody TCourse tCourse) {
        //设置添加时的时间
        tCourse.setCreateDate(new Date());
        //添加的用户
        TUser user = getSessionUser(SESSION_KEY_USER);

        //判断该用户是否存在,存在就设置学科userID
        if (user != null) {
            logger.info("当前用户："+user.toString());
            tCourse.setUserId(user.getId());
        } else {
            // 调试时，默认是管理员
            tCourse.setUserId(1);
        }
        int i = courseService.addCourse(tCourse);

        if (i > 0) {
            return AjaxResult.success("学科添加成功");
        }else {
            logger.error("addCourse 失败");
            return AjaxResult.error("学科添加失败");
        }

    }

    /*** 分页获取学科列表
     * * 调用响应请求分页数据方法
    */
    @PostMapping("course/findListByPage")
    @ResponseBody
    public TableDataInfo findListByPage(@RequestBody QueryPageBean queryPageBean){
        List<TCourse> courseList = courseService.findCourseList(queryPageBean);
        return getDataTable(courseList);
    }

    //更新学科
    @PostMapping("course/update")
    @ResponseBody
    public AjaxResult updateCourse(@RequestBody TCourse course){
        int rows = courseService.updateCourse(course);
        return toAjax(rows);
    }

    //查询所有学科列表(带有学科目录和学科标签)
    @GetMapping("course/findListAll")
    @ResponseBody
    public AjaxResult findListForQuestion(){
        try {
            List<TCourse> courseList = courseService.findListAll();
            return AjaxResult.success(courseList);
        }catch (Exception e){
            logger.error(e.getMessage());
            return AjaxResult.error("查询失败");
        }
    }
}
